package com.example.ioc_application.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.ioc_application.MainActivity;
import com.example.ioc_application.consts.ApiConst;
import com.example.ioc_application.utils.HttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

public class Dht11Service extends Service {

    public class Binder extends android.os.Binder {
        public Dht11Service getService() {
            return Dht11Service.this;
        }
    }

    public interface Callback {
        void onDataChange(JSONObject json) throws JSONException;
    }

    private Callback callback;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Runnable dht11Thread = () -> {
            while (true) {
                try {
                    JSONObject json = new JSONObject(HttpUtils.send(ApiConst.DHT11));
                    Log.d("DHT11Service请求后台接口", json.toString());
                    if (callback != null) {
                        callback.onDataChange(json);
                    }
                    Thread.sleep(3000);
                } catch (JSONException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(dht11Thread).start();
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("DHT11Service", "被销毁");
    }
}
